package cn.zwx.zookeeper.config.example.event;

import cn.zwx.zookeeper.config.example.support.ConfigurationPropertiesBeans;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

/**
 * 监听我们自己发布的时间 进行重新覆盖@Value的值
 *  @author zhangwenxue
 */
@Component
public class ConfigurationPropertiesReBinder implements ApplicationListener<EnvironmentChangeEvent> {

    private static final Logger logger = LoggerFactory.getLogger(ConfigurationPropertiesReBinder.class);


    private ConfigurationPropertiesBeans beans;

    private Environment environment;

    public ConfigurationPropertiesReBinder(ConfigurationPropertiesBeans beans, Environment environment) {
        this.beans=beans;
        this.environment=environment;
    }

    @Override
    public void onApplicationEvent(EnvironmentChangeEvent event) {
        logger.info("收到environment变更事件");
        rebind();
    }

    public void rebind(){
        this.beans.getFieldMapper().forEach((k,v)->{
            v.forEach(f->f.resetValue(environment));
        });
    }
}
